{{ $category := selectList "category" "" 1 1000 "* FROM category order by sortNo desc" }}
{{ $convertJson := convertType  $category.Data "object" "json" }}
{{template "admin/header.html"}}
<title>{{T "Content Navigation"}} - GPRESS</title>
<link href="{{basePath}}admin/css/tree.css" rel="stylesheet">
<style>
	table {
		width: 100%;
		flex: 1;
		overflow: auto;
	}
	table td {
	width: fit-content;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	word-break: break-all;
	vertical-align: middle !important;
	max-width: 200px;
}

</style>
{{template "admin/bodystart.html"}}

<div class="layui-col-space10" style="height: 100%;">
	<div class="layui-col-md3" style="height: 100%;">
		<div class="layui-panel" style="height: 100%; padding: 5px;overflow: auto;">
			<div class="layui-form-item" style="text-align: center;padding: 10px;">
				<a href="{{basePath}}admin/category/save" class="layui-btn layui-bg-blue">+{{T "Add Top Navigation"}}</a>
			</div>

			<div class="tree" id="tree">
				<details open="">
					<summary id="allContent" class="tree-item"><a id="all_tree_a" href="{{basePath}}admin/content/list?id=&pageNo=1">{{T "All Content"}}</a>
					</summary>
				</details>
			</div>
		</div>
	</div>
	<div class="layui-col-md9">
		<div style="height: 100%;">
				<form id="listForm" action="{{basePath}}admin/{{.UrlPathParam}}/list" method="GET">
					<input type="hidden" id="pageNo" name="pageNo" value="{{.Page.PageNo}}">
					<input type="hidden" id="id" name="id" value="">
					<div class="layui-input-group">
						<input type="text" id="q" name="q" placeholder='{{T "Search"}}' class="layui-input">
						<div class="layui-input-split layui-input-suffix" style="cursor: pointer;">
							<i class="layui-icon layui-icon-search" onclick="submitListForm();"></i>
						</div>
						<div class="layui-input-suffix">
							<a href="{{basePath}}admin/{{.UrlPathParam}}/save" class="layui-btn layui-bg-blue">{{T "Add Content"}}</a>
						</div>
					</div>
				</form>
				<table class="layui-table table-content" id="table_list" lay-filter="parse-table-list">
					<thead>
						<tr>
							<th width="25%">{{T "URL Path"}}</th>
							<th width="29%">{{T "Title"}}</th>
							<th width="10%">{{T "Navigation Menu"}}</th>
							<th width="7%">{{T "Sort"}}</th>
							<th width="12%">{{T "Status"}}</th>
							<th width="17%">{{T "Actions"}}</th>
						</tr>
					</thead>
					<tbody>
						<!-- 循环所有的数据 -->
						{{ range $i,$v := .Data }}
						<tr>
							<!-- 获取每一列的值 -->
							<td title="{{basePath}}{{trimPrefixSlash $v.Id }}"><a href="{{basePath}}{{ trimPrefixSlash $v.Id }}" style="cursor: pointer;" target="_blank">{{basePath}}{{trimPrefixSlash .Id }}</a></td>
							<td title="{{ .Title }}"><a href="{{basePath}}admin/{{$.UrlPathParam}}/update?id={{.Id}}" style="cursor: pointer;"> {{ .Title }} </a></td>
							<td title="{{ .CategoryName }}"> {{ .CategoryName }}</td>
							<td> {{ .SortNo }}</td>
							<td>
								{{if eq .Status 0 }}
								{{T "Link Access"}}
								{{else if eq .Status 1 }}
								{{T "Public"}}
								{{else if eq .Status 2 }}
								{{T "Top"}}
								{{else if eq .Status 3 }}
								{{T "Private"}}
								{{else}}
								{{T "Unknown"}}
								{{end}}
							</td>
							<td>
								<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" title='{{T "Preview"}}'>
									<a href="{{basePath}}admin/{{$.UrlPathParam}}/look?id={{.Id}}" target="_blank">
										<i class="layui-icon layui-icon-eye"></i>
									</a>
								</button>
								<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" title='{{T "Edit"}}'>
									<a href="{{basePath}}admin/{{$.UrlPathParam}}/update?id={{.Id}}">
										<i class="layui-icon layui-icon-edit"></i>
									</a>
								</button>
								<button type="button" class="layui-btn layui-btn-primary layui-btn-xs"
									onclick="deleteFunc('{{$v.Id}}','{{basePath}}admin/{{$.UrlPathParam}}/delete');" title='{{T "Delete"}}'>
									<i class="layui-icon layui-icon-delete"></i>
								</button>
							</td>
						</tr>
						{{end }}
					</tbody>
				</table>
				<div id="div-list-page"></div>
			</div>
	</div>

  </div>
{{template "admin/bodyend.html"}}

<script>
	var layer;
	var $;
	layui.use(function () {
		//var table = layui.table;
		layer = layui.layer;
		$ = layui.jquery;
		var laypage = layui.laypage;
		var dropdown = layui.dropdown;
		const categoryData = JSON.parse("{{ $convertJson }}");
		const treeData = buildTree(categoryData);
		// 将树形结构渲染到页面上
		renderTree($('#tree'), treeData);

		const query = window.location.search;
		const params = new URLSearchParams(query)
		var q = params.get("q")
		if (q) {
			$("#q").val(q)
		}
		var id = params.get("id")
		if (id && id != "") {
			$("#id").val(id)
		}

		//选中高亮
		if (id && id != "") {//被选中
			var codes = id.split("/");
			var codeId="/";
			for (i = 0; i < codes.length; i++) {
				var code = codes[i];
				//console.log(code)
				if (code != "") {
					codeId=codeId+code+"/"
					document.getElementById("tree_a_" + codeId).style="color:#1e9fff";
				}
			}

		} else {
			document.getElementById("all_tree_a").style="color:#1e9fff";
		}

		// 导航菜单下来事件绑定
		dropdown.render({
			elem: '.tips-dropdown',
			trigger: 'hover',
			data: [{ id: "1", title: '{{T "Add Content"}}' }, { id: "2", title: '{{T "Add Sub Navigation"}}' }, { id: "3", title: '{{T "Edit Navigation"}}' }, { id: "4", title: '{{T "Delete Navigation"}}' }],
			click: function (data, othis) {
				let categoryId = this.elem.attr("id");
				if (data.id == "1") {
					window.location.href = basePath + 'admin/content/save?categoryID=' + categoryId;
				} else if (data.id == "2") {
					window.location.href = basePath + 'admin/category/save?pid=' + categoryId;
				} else if (data.id == "3") {
					window.location.href = basePath + 'admin/category/update?id=' + categoryId;
				} else if (data.id == "4") {
					deleteFunc(categoryId, basePath + 'admin/category/delete');
				}
				//console.log(data.id); // 当前所点击的菜单项对应的数据
				//console.log(othis); // 当前所点击的菜单项元素对象
				//console.log(this.elem.attr("id")); // 当前组件绑定的目标元素对象，批量绑定中常用
			}
		});


		// 普通用法
		laypage.render({
			elem: 'div-list-page',
			count: "{{.Page.TotalCount}}",
			limit: "{{.Page.PageSize}}",
			curr: "{{.Page.PageNo}}",
			theme: '#1890ff',
			prev:'{{T "prev"}}',
			next:'{{T "next"}}',
			first:'{{T "first"}}',
			last:'{{T "last"}}',
			countText: ['{{T "Total"}} ',' {{T "records"}}'],
			skipText: ['{{T "Go to"}}', '{{T "pages"}}', '{{T "Confirm"}}'],
			layout: ['prev', 'page', 'next', 'count', 'skip'], // 功能布局
			jump: function (obj) {
				let pageNo = document.getElementById("pageNo").value - 0;
				if (pageNo != obj.curr) {
					document.getElementById("pageNo").value = obj.curr;
					submitListForm();
				}
			}
		});
	});

	function deleteFunc(id, url) {
		layer.confirm('{{T "Confirm deletion?"}}', {
			icon: 3,
			title: '{{T "Confirm"}}',
			btn: ['{{T "Confirm"}}', '{{T "Cancel"}}'] //按钮
		}, function () {
			$.ajax({
				type: 'post',
				url: url,
				data: { "id": id },
				success: function (res) {
					if (res.statusCode === 1) {
						layer.msg('{{T "Delete successful"}}', function () {
							location.reload();
						});
					}else{
						var message='{{T "Delete failed!"}}';
						if(!!res.message){
							message=message+res.message
						}
						layer.msg(message);
					}
				}
			});
		});
	}

	function submitListForm() {
		document.getElementById("listForm").submit();
	}
	// 渲染树形菜单结构
	function renderTree(container, data) {
		const details = container;
		data.forEach(node => {
			const detailsHtml = $(
				`<details id="details_${node.id}" open="">
					<summary class="tree-item">
						<a id="tree_a_${node.id}" href="{{basePath}}admin/content/list?id=${node.id}&pageNo=1">${node.name}</a> 
						<i class="layui-icon layui-icon-tips tips-dropdown" id="${node.id}" ></i>
					</summary>
				</details>`
			);

			if (node.children) {
				renderTree(detailsHtml, node.children);
			}
			details.append(detailsHtml);
		});
		container.append(details);
	}

	// 平行数据组装树形结构数据
	function buildTree(data) {
		const roots = data.filter(item => !item.pid);// 找到没有父节点的项，即顶级节点
		// 递归构建树
		function buildHierarchy(parent) {
			const children = data.filter(item => item.pid === parent.id);
			if (children.length > 0) {
				parent.children = children;
				children.forEach(child => buildHierarchy(child));
			}
		}
		// 为每个顶级节点构建树
		roots.forEach(root => buildHierarchy(root));
		return roots;
	}

</script>